package com.gf.framework.mongo.lambda;

import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.gf.framework.mongo.entity.BaseEntity;
import java.util.Map;

/**
 * @author gaofei
 * @date 2022/5/28 21:11
 */
public class MongoLambdaUpdate<T extends BaseEntity> {
    private LambdaUpdate update;
    private MongoLambdaQuery<T> mongoLambdaQuery;

    MongoLambdaUpdate(MongoLambdaQuery<T> mongoLambdaQuery) {
        this.mongoLambdaQuery = mongoLambdaQuery;
    }

    public MongoLambdaUpdate<T> update(Map<String, Object> columns) {
        if (update == null) {
            update = new LambdaUpdate(columns);
        }
        columns.forEach((s, o) -> update.update(s, o));
        return this;
    }

    public MongoLambdaUpdate<T> update(SFunction<T, Object> column, Object value) {
        return update(MongoLambdaQuery.getFieldName(column), value);
    }

    public MongoLambdaUpdate<T> update(String column, Object value) {
        if (update == null) {
            update = new LambdaUpdate();
        }
        update.update(column, value);
        return this;
    }

    public boolean updateFirst() {
        return mongoLambdaQuery.mongoService.updateFirst(mongoLambdaQuery.getQuery(), update.getUpdate());
    }

    public boolean updateAll() {
        return mongoLambdaQuery.mongoService.update(mongoLambdaQuery.getQuery(), update.getUpdate());
    }
}
